<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use think\Db;
use app\admin\model\personal\AccountLog;
use app\admin\model\finance\FinanceLog;

/**
 * 收获订单管理
 *
 * @icon fa fa-reorder
 */
class Shorder extends Backend
{
    
    /**
     * Reorder模型对象
     * @var \app\admin\model\order\Reorder
     */
    protected $model = null;
    protected $receiving_model = null;
    protected $personal_model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\Reorder;
        $this->receiving_model = new \app\admin\model\goods\Receiving();
        $this->personal_model = new \app\admin\model\personal\Personal();
        $this->view->assign("statusList", $this->model->getStatusList());

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $op['reorder.status'] = ['not in',[30,31]];
            $list = $this->model
                    ->with(['personal','receiving'])
                    ->where($where)
                    ->where('order_user',2)
                    ->where($op)
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {
                $row->visible(['id','account','order_sn','invite','title','game','area','server','cross','num','price','status','ontime','order_user','priceAll']);
				$row->visible(['personal']);
				$row->getRelation('personal')->visible(['nickname','account']);
				$row->visible(['receiving']);
				$row->getRelation('receiving')->visible(['role_account','role_level']);
            }
            
            foreach($list as $k => $v){
                $list[$k]['priceAll'] = round($v['price']*$v['num'],2);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 详情
     */
    public function info($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row['receiving'] = $this->receiving_model::where('id', '=', $row['goods_id'])->find();
        $row['personal'] = $this->personal_model::where('id', '=', $row['uid'])
        ->field('account,is_real,id_card,name')->find();
        $row['role_server'] = Db::name('game_info')->where('id',$row['role_server'])->value('name');

        $uid = $_SESSION['think']['admin']['id'];
        $role_id = DB::name("auth_group_access")->where('uid',$uid)->find();
		$this->view->assign('group_access',$role_id['group_id']);

       
        // dump($sku);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 客服上传截图验证
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if($params['kf_images'] && $row['status'] == 11){
                        //如果客服已经上传截图，订单状态改为待确认
                        $params['status'] = 12;
                    }

                    //订单审核审核通过订单改为代发货。审核失败==买家原因撤单
                    // if($params['status'] == 7){
                    //     if($params['away'] == 2){
                    //         //卖家  商品下架
                    //         Db::name('goods')->where('id',$row['goods_id'])->update(['status'=>5]);
                    //     }
                    //     //商品库存退回
                    //     Db::name('goods')->where('id',$row['goods_id'])->setInc('stock',$row['num']);
                    //     //取消订单，资金退回冻结账户
                    //     $uinfo = $this->personal_model->where(['id'=>$row['buyid']])->field('balance,jy_balance')->find();
                    //     $log = new AccountLog();
                    //     $res = $log->addAccountLog($row['buyid'], '+'.$row['amount'], 5, '订单审核失败', 1,'',2);
                    //     if ($res !== false) {
                    //         Db::name('personal')->where(['id'=>$row['buyid']])->setInc( 'jy_balance', $row['amount'] );
                    //     }
                    //     $uinfo_after = $this->personal_model->where(['id'=>$row['buyid']])->field('balance,jy_balance')->find();
                    //     // dump($uinfo);
                    //     $financelog = new FinanceLog();
                    //     $financelog->addFinanceLog($row['buyid'],'订单审核失败',$uinfo['balance'],$uinfo['jy_balance'], $row['amount'], $uinfo_after['balance'],$uinfo_after['jy_balance'], '订单审核失败');
                    // }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("image", $row['kf_images']);
        return $this->view->fetch();
    }


    /**
     * 订单管控
     */
    public function manage($ids = null)
    {
        $row = $this->model->get($ids);
        $goods = Db::name('goods')->where(['id'=>$row['goods_id']])->field('is_safe,goods_class_type,method')->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $guadan_list = array();
        if($row['status'] == 5){
            $guadan_list = DB::name("guadan_reason")->where('order_id',$row['id'])->select();
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    if($params['status'] == 4){
                        if($row['status'] == 4){
                            $this->error('订单已撤单');
                        }

                        //商品库存退回
                        Db::name('receiving')->where('id',$row['goods_id'])->setInc('num',$row['num']);
                        //取消订单，资金退回余额
                        $uinfo = $this->personal_model->where(['id'=>$row['buyid']])->field('balance,jy_balance')->find();
                        $log = new AccountLog();
                        $res = $log->addAccountLog($row['buyid'], '+'.$row['prices'], 5, '订单申请撤单退回', 1,'',1);
                        if ($res !== false) {
                            Db::name('personal')->where(['id'=>$row['buyid']])->setInc( 'balance', $row['prices'] );
                        }
                        $uinfo_after = $this->personal_model->where(['id'=>$row['buyid']])->field('balance,jy_balance')->find();
                        // dump($uinfo);
                        $financelog = new FinanceLog();
                        $financelog->addFinanceLog($row['buyid'],'订单申请撤单退回',$uinfo['balance'],$uinfo['jy_balance'], $row['prices'], $uinfo_after['balance'],$uinfo_after['jy_balance'], $params['reason']);
                    }

                    if($params['status'] == 5){
                        if($row['status'] == 5){
                            $this->error('订单已完成');
                        }
                        $params['overtime'] = time();
                        //已完成的订单给卖家到账
                        $log = new AccountLog();
                        // 立即到账
                        $arrivaltime = time();
                        $goods_total_price = round($row['price'] * $row['num'], 2);
                        /*
                        $fee_info = $this->getAmount($goods_total_price, $goods['goods_class_type'], $goods['is_safe'], $row['xyg'], $goods['method'],$row['game_id'],$row['goods_type'],'','');*/
                        $money = $goods_total_price;
			// dump($money);
                        // exit;
                        //if($goods['is_safe']==1){
                        //}
                        //if($row['xyg']==2){
                            //$arrivaltime = time()+3*24*60*60;
                        //}
                        $log->addAccountLog($row['uid'], '+'.$money, 2, '售得', 0,$arrivaltime);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign([
            'row'=>$row,
            'guadan_list'=>$guadan_list
            ]);
        return $this->view->fetch();
    }
    
    /**
     * 查看聊天记录
     */
    public function chat($ids = null)
    {
        $ids = $ids?$ids:$this->request->post('id');
        $row = $this->model::where('id', '=', $ids)->field('id,order_sn,uid,buyid')->find();
        $list = DB::name('timely')->where(['order_sn'=>$row['order_sn']])->select();
        if($list){
            foreach($list as $k=>$v){
                if(strpos($v['content'],'https://780g.oss-cn-zhangjiakou.aliyuncs.com') !== false){
                    //消息内容为图片
                    $list[$k]['c_type'] = 1;
                }else{
                    //消息内容为文字
                    $list[$k]['c_type'] = 2;
                }
                if($v['fromUserId']==$row['buyid']){
                    $list[$k]['title'] = '买家';
                    $list[$k]['type'] = 1;
                }else{
                    $list[$k]['title'] = '卖家';
                    $list[$k]['type'] = 2;
                }
            }
        }
        // dump($list);
        if ($this->request->isAjax()) {
            return json($list);
        }
        $this->view->assign([
                "list" => $list,
                "row" => $row,
        ]);
        return $this->view->fetch();
        
    }
    
    
    /**
     * 查看聊天记录
     */
    public function chatlist($ids = null)
    {
        $ids = $ids?$ids:$this->request->post('id');
        $row = $this->model::where('id', '=', $ids)->field('order_sn,uid,buyid')->find();
        $list = DB::name('timely')->where(['order_sn'=>$row['order_sn']])->select();
        if($list){
            foreach($list as $k=>$v){
                if(strpos($v['content'],'https://780g.oss-cn-zhangjiakou.aliyuncs.com') !== false){
                    //消息内容为图片
                    $list[$k]['c_type'] = 1;
                }else{
                    //消息内容为文字
                    $list[$k]['c_type'] = 2;
                }
                if($v['fromUserId']==$row['buyid']){
                    $list[$k]['title'] = '买家';
                    $list[$k]['type'] = 1;
                }else{
                    $list[$k]['title'] = '卖家';
                    $list[$k]['type'] = 2;
                }
            }
        }
        return json($list);
    }

    /**
     * 客服联系买/卖家
     */
    public function online($ids = null)
    {
        $row = $this->model::where('id', '=', $ids)->field('order_sn,id,uid,buyid')->find();
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
